package com.ekingstar.hedss.action;

import java.io.BufferedOutputStream;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.config.Action;
import org.apache.struts2.config.Result;
import org.apache.struts2.config.Results;

import com.opensymphony.xwork2.ActionSupport;
import com.ekingstar.framework.security.UserUtil;
import com.ekingstar.hedss.domain.HedssZlfj;
import com.ekingstar.hedss.service.IHedssService;

@Action(name = "download", namespace = "/download")
@Results( {
	@Result(name = "nologin", value = "/user/nologin.jsp")})
public class DownloadAction extends ActionSupport {		
	private static final long serialVersionUID = 1L;
	
	private HedssZlfj zlfj;
	private IHedssService hedssService;
	
	public String input(){
				
		return "input";
	}	
		
	public String execute(){
		boolean logged = UserUtil.isLogged();
		if (!logged ){
			return "nologin";
		}
		
		HttpServletResponse response = ServletActionContext.getResponse();
		
		if(zlfj==null)
			return null;
		
		try {
			zlfj=hedssService.getZlfj(zlfj.getId());
			
			response.setContentType("application/x-msdownload");
			response.addHeader("Content-Disposition", "attachment; filename="
					+ new String(zlfj.getName().getBytes(),"ISO8859-1"));
			
			ServletOutputStream out = response.getOutputStream();			
			BufferedOutputStream bos = null;
			try {		
				
				HedssZlfj downfile=hedssService.getZlfj(zlfj.getId());				
				bos = new BufferedOutputStream(out);
				byte[] downdata = downfile.getContent();
				
				bos.write(downdata,0,downdata.length);
				bos.flush();
				
			} catch (Exception e) {
				e.printStackTrace();
			} finally {				
				if (bos != null)
					bos.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
	public HedssZlfj getZlfj() {
		return zlfj;
	}

	public void setZlfj(HedssZlfj zlfj) {
		this.zlfj = zlfj;
	}

	public IHedssService getHedssService() {
		return hedssService;
	}

	public void setHedssService(IHedssService hedssService) {
		this.hedssService = hedssService;
	}

	
}
